﻿
using HBase;
using hconnect;
using MongoDB.Bson;
using Net.http;
using System;
using System.Collections.Generic;
using System.Linq;


namespace hCommand {
    [RoutePrefix("sign")]
    public class SignServer :BaseApiController {



        IWCSServer wcsServer = WMSDalFactray.getDal<IWCSServer>();
        IMServer mGStatuslog = GuidangFactray.getDal<IMServer>();
        [HttpGet, Route("stn")]
        public BaseResult showStn() {
            List<BStn> physicalStns = wcsServer.GetPhysicalStns();
            List<BStnRelation> physicalStnRelations = wcsServer.GetPhysicalStnRelation();

            return BaseResult.Ok(new { physicalStns ,physicalStnRelations });
        }





        [HttpGet, Route("addStn/{idStr}/{x}/{y}")]
        public BaseResult addStn(String idStr ,int x ,int y) {

            String[] ids = idStr.Split(',');

            if( ids.Length == 1 ) {
                List<BStn> physicalStns = wcsServer.GetPhysicalStns();
                foreach( BStn stnOld in physicalStns ) {
                    if( stnOld.id == int.Parse(ids[0]) ) {
                        wcsServer.delete(stnOld);
                    }
                }

            } else {
                int b = int.Parse(ids[0]);
                int e = int.Parse(ids[1]);
                for( int id = b;id <= e;id++ ) {
                    BStn stn = new BStn();

                    stn.id = id;
                    stn.x = x;
                    stn.y = y;
                    stn.isKeyPoint = 0;
                    stn.area = id+"";
          
                    stn.angle = 0;
                    stn.length = 60;
                    stn.distance = 5000;
                    wcsServer.insert(stn);
                }


            }



            return showStn();
        }

        [HttpGet, Route("key/{id}")]
        public BaseResult key(int id) {
            List<BStn> physicalStns = wcsServer.GetPhysicalStns();
            foreach( BStn stn in physicalStns ) {
                if( stn.id == id ) {
                    stn.isKeyPoint = ( byte ) (stn.isKeyPoint == 1 ? 0 : 1);

                    wcsServer.updateNotNull(stn);
                }
            }
            return showStn();
        }

        [HttpGet, Route("angle/{id}")]
        public BaseResult angle(int id) {
            List<BStn> physicalStns = wcsServer.GetPhysicalStns();
            foreach( BStn stn in physicalStns ) {
                if( stn.id == id ) {
                    stn.angle += 90;
                    stn.angle %= 360;
                    wcsServer.updateNotNull(stn);
                }
            }
            return showStn();
        }
        [HttpGet, Route("addLine/{begin}/{end}")]
        public BaseResult addLine(int begin ,int end) {

            List<BStnRelation> physicalStnRelations = wcsServer.GetPhysicalStnRelation();
            foreach( BStnRelation re in physicalStnRelations ) {
                if( re.src == begin && re.next == end ) {
                    wcsServer.delete(re);
                    return showStn();
                }
            }
            addStnRelation(begin ,end);
            return showStn();
        }
        void addStnRelation(int begin ,int end ,int dis = 6000) {
            if( begin == end ) {
                return;

            }
            BStnRelation stn = new BStnRelation() { src = begin ,next = end };
           
            stn.deviceType = "TaskCarrier";
  
            stn.b = dis;
         
            wcsServer.insertNotNull(stn);
        }
        [HttpGet, Route("standard/{taskNo}")]
        public BaseResult standard(int taskNo) {
            List<TaskTrail> list = queryAll(taskNo);
            list = list.OrderBy(o => new { o.begin ,o.end }).ToList();
            for( int i = 0;i < list.Count - 1;i++ ) {
                TaskTrail b = list[i];
                TaskTrail e = list[i + 1];

                int dis = getTime(e.begin ,b.end);

                addStnRelation(b.eId ,e.eId ,dis);
                if( i == 0 ) {
                    int disFirst = getTime(Convert.ToDateTime(b.begin).Ticks ,min(e.begin ,b.end));
                } else {
                    int dis1 = getTime(max(list[i - 1].end ,b.begin) ,min(e.begin ,b.end));
                    if( i == list.Count - 2 ) {
                        int disLast = getTime(max(b.end ,e.begin) ,Convert.ToDateTime(e.end).Ticks);
                    }
                }
            }
            return BaseResult.Ok("成功");
        }


        static TaskTrail getTrail(List<TaskTrail> list ,int stn) {
            foreach( TaskTrail tt in list ) {
                if( tt.eId == stn ) {
                    return tt;
                }

            }
            TaskTrail trail = new TaskTrail();
            trail.eId = stn;
            list.Add(trail);
            return trail;
        }
        public List<TaskTrail> queryAll(int taskNo) {



            List<BsonDocument> result = mGStatuslog.queryAll("status" ,"{keyCode:"+ taskNo + "}"  ,"{time,-1}");
            List<TaskTrail> list = new List<TaskTrail>();
            foreach( BsonDocument bd in result ) {
                String keyCode = bd.GetValue("keyCode").ToString();
                String time = bd.GetValue("time").ToString();
                String eId = JsonUtil.getStr(bd ,"eId");

                if( eId.StartsWith("STN") ) {
                    String stn = eId.Substring(4);
                    TaskTrail trail = getTrail(list ,int.Parse(stn));
                    String value = JsonUtil.getStr(bd ,"taskNo");
                    if( value.StartsWith(taskNo + "") ) {
                        trail.begin = time;

                    } else if( value.EndsWith(taskNo + "") ) {
                        trail.end = time;
                    }
                } else {
                    String finishFlag = JsonUtil.getStr(bd ,"finishFlag");
                    TaskTrail trail = getTrail(list ,int.Parse(eId));
                    if( finishFlag == "2" ) {
                        trail.begin = time;
                    } else if( finishFlag == "9" ) {
                        trail.end = time;
                    }


                }
            }
            return list;
        }


        public class TaskTrail {
            public int eId;
            public String begin;
            public String end;
        }

        long max(String begin ,String end) {
            long t1 = Convert.ToDateTime(begin).Ticks;
            long t2 = Convert.ToDateTime(end).Ticks;
            return Math.Max(t1 ,t2);
        }
        long min(String begin ,String end) {
            long t1 = Convert.ToDateTime(begin).Ticks;
            long t2 = Convert.ToDateTime(end).Ticks;
            return Math.Min(t1 ,t2);
        }
        int getTime(String begin ,String end) {
            long time1 = Convert.ToDateTime(begin).Ticks - Convert.ToDateTime(end).Ticks;
            int dis1 = ( int ) time1 / 10000;
            dis1 = Math.Max(dis1 ,0);
            return dis1;
        }
        int getTime(long begin ,long end) {
            long time1 = begin - end;
            int dis1 = ( int ) time1 / 10000;
            dis1 = Math.Max(dis1 ,0);
            return dis1;
        }
        [HttpGet, Route("updatePos/{x}/{y}/{eid}")]
        public BaseResult updatePos(String eid ,int x ,int y) {

            wcsServer.updatePos(x ,y ,eid);
            return showStn();
        }

        [HttpGet, Route("updateX/{x}/{eid}")]
        public BaseResult updateX(String eid ,int x) {

            wcsServer.updatePos(x ,0 ,eid);
            return showStn();
        }

        [HttpGet, Route("updateY/{y}/{eid}")]
        public BaseResult updateY(String eid ,int y) {

            wcsServer.updatePos(0 ,y ,eid);
            return showStn();
        }

        [HttpGet, Route("update/{eid}/{x}/{y}/{dis}")]
        public BaseResult update(String eid ,String x ,String y ,String dis) {
            String[] idarr = eid.Split(',');

            String[] xarr = x.Split(',');
            String[] yarr = y.Split(',');
            String[] lenArr = dis.Split(',');

            for( int i = 0;i < idarr.Length;i++ ) {

                BStn stn = new BStn() { id = int.Parse(idarr[i]) };
                if( lenArr.Length == idarr.Length ) {
                    stn.length = int.Parse(lenArr[i]);
                }

                if( xarr.Length == idarr.Length ) {
                    stn.x = int.Parse(xarr[i]);
                }

                if( yarr.Length == idarr.Length ) {
                    stn.y = int.Parse(yarr[i]);
                }
                wcsServer.updatePhysicalStn(stn);

            }


            return showStn();
        }

        [HttpGet, Route("delete/{eid}")]
        public BaseResult delete(String eid) {
            String[] idarr = eid.Split(',');

        

            for (int i = 0; i < idarr.Length; i++) {

                BStn stn = new BStn() { id = int.Parse(idarr[i]) };
               
                wcsServer.delete(stn);

            }


            return showStn();
        }
        [HttpGet, Route("data")]
        public BaseResult data() {
            return BaseResult.Ok(StatusCache.dict);
        }



    }
}
